package com.gitee.baqkft.code.utils;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Random;

/**
 * 密码工具
 * @Author: chenmingcai
 * @Date 2023/10/16 21:05
 **/

public class PasswdUtils
{
    /**
     * 生成随机密码
     * @param length 密码长度
     * @param upper 大写字母
     * @param lower 小写字母
     * @param digits    数字
     * @param hasSymbols   符号
     * @return 密码字符串
     */
    public static String makeRandomPasswd(int length, boolean upper, boolean lower,
                                          boolean digits, boolean hasSymbols)
    {
        final String upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        final String lowerAlphabet = "abcdefghijklmnopqrstuvwxyz";
        final String symbols = "_&@#$^*+";

        final Random random = new Random();
        final StringBuffer buffer = new StringBuffer();

        final int symbolPos = random.nextInt(length);
        int index = 0;
        do
        {

            int idx;
            if(hasSymbols && symbolPos == index)
            {
                //符号
                idx = random.nextInt(symbols.length());
                buffer.append(symbols.charAt(idx));
            }
            else if(upper && index % 6 == 0)
            {
                //大写
                idx = random.nextInt(upperAlphabet.length());
                buffer.append(upperAlphabet.charAt(idx));
            }
            else if(lower && index % 3 == 0)
            {
                //小写
                idx = random.nextInt(lowerAlphabet.length());
                buffer.append(lowerAlphabet.charAt(idx));
            }
            else if(digits)
            {
                buffer.append(random.nextInt(10));
            }
            index++;
        }while (buffer.length() < length);

        return buffer.toString();
    }

    /**
     * 加密字符串
     * @param text
     * @return
     */
    public static String encodeByBCrypt(final String text)
    {
        final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder.encode(text);
    }
}
